<template>
  <div class="blog-detail">
    <!-- 导航栏 -->
    <Navbar />

    <!-- 主内容 -->
    <main class="main-wrapper">
      <div v-if="loading" class="loading-state">
        <el-icon class="is-loading" :size="48"><Loading /></el-icon>
        <p>加载中...</p>
      </div>

      <article v-else-if="blog" class="article-container">
        <!-- 顶部操作栏 -->
        <div class="article-actions-bar">
          <button class="btn-back" @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            <span>返回</span>
          </button>
          <div v-if="isMyBlog" class="action-buttons">
            <button class="btn-edit-header" @click="editBlog">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </button>
          </div>
        </div>

        <!-- 文章头部 -->
        <header class="article-header">
          <!-- 标题 -->
          <h1 class="article-title">{{ blog.title }}</h1>

          <!-- 元信息 -->
          <div class="article-meta">
            <span class="author-info">作者：<strong>{{ blog.author || '匿名用户' }}</strong></span>
            <span class="separator">·</span>
            <span class="publish-date">{{ formatDate(blog.publishedAt || blog.createdAt) }}</span>
            <span class="separator">·</span>
            <span class="read-time">{{ estimateReadTime(blog.content) }} 分钟阅读</span>
          </div>
        </header>

        <!-- 文章封面 -->
        <div v-if="blog.coverImage" class="article-cover">
          <img :src="blog.coverImage" :alt="blog.title" />
        </div>

        <!-- 文章内容 -->
        <div class="article-content" v-html="formattedContent"></div>

        <!-- 文章底部 -->
        <footer class="article-footer">
          <!-- 分类和标签 -->
          <div class="footer-taxonomy">
            <div v-if="blog.category" class="taxonomy-item">
              <span class="taxonomy-label">分类：</span>
              <span class="taxonomy-value category-link">{{ blog.category }}</span>
            </div>
            <div v-if="blog.tags && blog.tags.length > 0" class="taxonomy-item">
              <span class="taxonomy-label">标签：</span>
              <div class="taxonomy-value">
                <span v-for="(tag, index) in blog.tags" :key="tag" class="tag-link">
                  {{ tag }}<span v-if="index < blog.tags.length - 1" class="tag-separator">、</span>
                </span>
              </div>
            </div>
          </div>

          <!-- 操作和统计 -->
          <div class="footer-actions-stats">
            <div class="footer-actions">
              <button class="action-btn">
                <el-icon><Star /></el-icon>
                <span>收藏</span>
              </button>
              <button class="action-btn">
                <el-icon><Share /></el-icon>
                <span>分享</span>
              </button>
            </div>
            <div class="footer-stats">
              <span class="stat-item">阅读({{ blog.viewCount || 0 }})</span>
              <span class="stat-item">收藏({{ blog.favoriteCount || 0 }})</span>
              <span class="stat-item">评论({{ blog.commentCount || 0 }})</span>
            </div>
          </div>
        </footer>

        <!-- 评论区 -->
        <section class="comments-section">
          <h3 class="section-title">
            <el-icon><ChatDotRound /></el-icon>
            评论 <span class="comment-count">({{ blog.commentCount || 0 }})</span>
          </h3>
          <div class="empty-comments">
            <el-icon :size="48"><ChatLineRound /></el-icon>
            <p>暂无评论，快来抢沙发吧~</p>
          </div>
        </section>
      </article>

      <div v-else class="error-state">
        <el-icon :size="80"><WarningFilled /></el-icon>
        <p>文章不存在或已被删除</p>
        <a class="btn-back-home" href="/" target="_self">
          返回首页
        </a>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Star,
  View,
  Share,
  ChatDotRound,
  ChatLineRound,
  WarningFilled,
  Loading,
  Edit,
  ArrowLeft
} from '@element-plus/icons-vue'
import { getBlogDetail } from '../api/blog'
import Navbar from '../components/Navbar.vue'
import { parseMarkdown, estimateReadTime as calcReadTime } from '../utils/markdown'
import { normalizeTags } from '../utils/tags'

const route = useRoute()
const router = useRouter()

const blog = ref(null)
const loading = ref(false)

// 获取当前登录用户信息
const currentUser = computed(() => {
  const user = localStorage.getItem('user')
  return user ? JSON.parse(user) : {}
})

// 判断是否是当前用户的博客
const isMyBlog = computed(() => {
  if (!blog.value || !currentUser.value.id) {
    return false
  }
  return blog.value.userId === currentUser.value.id
})

// 将 Markdown 转换为 HTML
const formattedContent = computed(() => {
  if (!blog.value || !blog.value.content) {
    return ''
  }
  return parseMarkdown(blog.value.content)
})

const fetchBlogDetail = async () => {
  loading.value = true
  try {
    const id = parseInt(route.params.id)
    const res = await getBlogDetail(id)
    
    const blogData = res.data || res
    
    // 使用公共工具处理标签
    const tagsArray = normalizeTags(blogData.tags)
    console.log('详情页-原始tags:', blogData.tags, '处理后:', tagsArray)
    
    blog.value = {
      ...blogData,
      tags: tagsArray,
      author: blogData.userName || blogData.author || '匿名用户',
      category: blogData.categoryName || blogData.category || null,
      viewCount: blogData.viewCount || 0,
      favoriteCount: blogData.favoriteCount || 0,
      commentCount: blogData.commentCount || 0
    }
    
    console.log('详情页加载的博客数据:', blogData)
    console.log('处理后的标签数组:', tagsArray)
  } catch (error) {
    console.error('获取博客详情失败:', error)
    blog.value = null
  } finally {
    loading.value = false
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 使用公共工具函数
const estimateReadTime = calcReadTime

const getUserAvatar = (username) => {
  if (!username) return ''
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${username}`
}

// 编辑博客
const editBlog = () => {
  router.push(`/edit/${blog.value.id}`)
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  fetchBlogDetail()
})
</script>

<style scoped>
/* 全局样式 */
.blog-detail {
  min-height: 100vh;
  background: var(--bg-primary);
}

/* 主内容 */
.main-wrapper {
  max-width: 100%;
  margin: 0 auto;
  padding: 0;
  min-height: calc(100vh - 60px);
  background: var(--bg-card);
}

/* 文章容器 */
.article-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 32px 240px 80px;
  min-height: calc(100vh - 60px);
}

/* 顶部操作栏 */
.article-actions-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0 24px 0;
  margin-bottom: 24px;
  border-bottom: 1px solid var(--border-light);
}

.btn-back {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border: 1.5px solid var(--border-normal);
  border-radius: 8px;
  background: var(--bg-tertiary);
  color: var(--text-secondary);
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-back:hover {
  border-color: var(--primary-start);
  color: var(--primary-start);
  background: var(--bg-hover);
  transform: translateX(-2px);
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-edit-header {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 18px;
  border: none;
  border-radius: 8px;
  background: var(--gradient-primary);
  color: var(--bg-primary);
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: var(--shadow-glow);
}

.btn-edit-header:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 212, 255, 0.5);
}

.btn-edit-header:active {
  transform: translateY(0);
}

.btn-edit-header .el-icon {
  font-size: 14px;
}

/* 文章头部 */
.article-header {
  margin-bottom: 40px;
}

.article-title {
  font-size: 36px;
  font-weight: 800;
  color: var(--text-bright);
  line-height: 1.3;
  margin: 0 0 24px 0;
  letter-spacing: -0.02em;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.article-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--border-normal);
  font-size: 13px;
  color: var(--text-tertiary);
}

.author-info {
  color: var(--text-secondary);
}

.author-info strong {
  color: var(--text-bright);
  font-weight: 600;
}

.publish-date,
.read-time {
  color: var(--text-tertiary);
}

.separator {
  color: var(--text-tertiary);
  opacity: 0.5;
}

/* 文章封面 */
.article-cover {
  margin-bottom: 40px;
  border-radius: 16px;
  overflow: hidden;
  border: 1px solid var(--border-normal);
  box-shadow: var(--shadow-md);
}

.article-cover img {
  width: 100%;
  height: auto;
  display: block;
}

/* 文章内容 */
.article-content {
  font-size: 17px;
  line-height: 1.8;
  color: var(--text-primary);
  margin-bottom: 80px;
  margin-top: 48px;
  max-width: 100%;
  letter-spacing: 0.02em;
  word-spacing: 0.05em;
  text-align: justify;
  text-justify: inter-word;
}

.article-content :deep(h1),
.article-content :deep(h2),
.article-content :deep(h3),
.article-content :deep(h4) {
  color: var(--text-bright);
  font-weight: 700;
  margin: 2em 0 0.8em 0;
  line-height: 1.4;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.article-content :deep(h1) { 
  font-size: 32px; 
  margin-top: 2.5em;
}
.article-content :deep(h2) { 
  font-size: 26px; 
  margin-top: 2.2em;
}
.article-content :deep(h3) { 
  font-size: 22px;
  margin-top: 2em;
}
.article-content :deep(h4) { 
  font-size: 19px;
  margin-top: 1.8em;
}

.article-content :deep(p) {
  margin: 0 0 1.5em 0;
  color: var(--text-primary);
  text-align: justify;
}

.article-content :deep(a) {
  color: var(--primary-start);
  text-decoration: none;
  border-bottom: 1px solid rgba(0, 212, 255, 0.3);
  transition: all 0.3s;
}

.article-content :deep(a:hover) {
  border-bottom-color: var(--primary-start);
  text-shadow: 0 0 10px rgba(0, 212, 255, 0.5);
}

.article-content :deep(code) {
  background: var(--bg-tertiary);
  padding: 4px 10px;
  border-radius: 6px;
  font-size: 0.9em;
  color: var(--primary-light);
  font-family: 'JetBrains Mono', 'Fira Code', 'Monaco', 'Courier New', monospace;
  border: 1px solid var(--border-normal);
  font-weight: 600;
}

.article-content :deep(pre) {
  background: var(--bg-secondary);
  padding: 1.5em;
  border-radius: 8px;
  overflow-x: auto;
  margin: 2em 0;
  border: 1px solid var(--border-normal);
  box-shadow: var(--shadow-md);
  line-height: 1.6;
}

.article-content :deep(pre code) {
  background: none;
  color: var(--text-bright);
  padding: 0;
  border: none;
}

.article-content :deep(blockquote) {
  border-left: 3px solid var(--primary-start);
  padding-left: 1.5em;
  margin: 2em 0;
  color: var(--text-secondary);
  font-style: italic;
  background: rgba(0, 212, 255, 0.05);
  padding: 1.2em 1.5em;
  border-radius: 0 6px 6px 0;
  font-size: 0.95em;
}

.article-content :deep(ul),
.article-content :deep(ol) {
  margin: 1.5em 0;
  padding-left: 1.8em;
}

.article-content :deep(li) {
  margin: 0.6em 0;
  color: var(--text-primary);
  line-height: 1.8;
}

.article-content :deep(li + li) {
  margin-top: 0.8em;
}

.article-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 2em auto;
  display: block;
  border: 1px solid var(--border-normal);
  box-shadow: var(--shadow-md);
}

.article-content :deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 24px 0;
  background: var(--bg-tertiary);
  border-radius: 8px;
  overflow: hidden;
}

.article-content :deep(th),
.article-content :deep(td) {
  padding: 12px;
  border: 1px solid var(--border-normal);
  text-align: left;
}

.article-content :deep(th) {
  background: var(--bg-hover);
  color: var(--text-bright);
  font-weight: 700;
}

/* 文章底部 */
.article-footer {
  padding: 20px 0;
  border-top: 1px solid var(--border-normal);
  margin-bottom: 40px;
}

/* 分类和标签 */
.footer-taxonomy {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-normal);
}

.taxonomy-item {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
}

.taxonomy-item:last-child {
  margin-bottom: 0;
}

.taxonomy-label {
  color: var(--text-secondary);
  font-weight: 500;
  flex-shrink: 0;
}

.taxonomy-value {
  color: var(--text-primary);
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.category-link {
  color: var(--primary-start);
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 500;
}

.category-link:hover {
  color: var(--primary-light);
  text-decoration: underline;
}

.tag-link {
  color: var(--primary-start);
  cursor: pointer;
  transition: all 0.2s;
}

.tag-link:hover {
  color: var(--primary-light);
  text-decoration: underline;
}

.tag-separator {
  color: var(--text-tertiary);
}

/* 操作和统计 */
.footer-actions-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.footer-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 16px;
  border: 1px solid var(--border-normal);
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.action-btn:hover {
  border-color: var(--primary-start);
  color: var(--primary-start);
  background: var(--bg-hover);
}

.action-btn .el-icon {
  font-size: 14px;
}

.footer-stats {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 13px;
  color: var(--text-secondary);
}

.stat-item {
  color: var(--text-secondary);
}

/* 评论区 */
.comments-section {
  padding-top: 40px;
  border-top: 2px solid var(--border-normal);
}

.section-title {
  font-size: 24px;
  font-weight: 700;
  color: var(--text-bright);
  margin: 0 0 32px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.section-title .el-icon {
  color: var(--primary-start);
  font-size: 28px;
}

.comment-count {
  color: var(--text-tertiary);
  font-size: 20px;
}

.empty-comments {
  text-align: center;
  padding: 80px 20px;
  color: var(--text-tertiary);
}

.empty-comments .el-icon {
  color: var(--text-tertiary);
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-comments p {
  font-size: 15px;
  margin: 0;
}

/* 加载和错误状态 */
.loading-state,
.error-state {
  text-align: center;
  padding: 120px 20px;
  color: var(--text-tertiary);
}

.loading-state .el-icon,
.error-state .el-icon {
  color: var(--primary-start);
  margin-bottom: 24px;
}

.loading-state p,
.error-state p {
  font-size: 18px;
  margin: 0 0 32px 0;
  color: var(--text-secondary);
}

.btn-back-home {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 14px 36px;
  border: none;
  border-radius: 12px;
  background: var(--gradient-primary);
  color: var(--bg-primary);
  font-size: 15px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: var(--shadow-glow);
  text-decoration: none;
}

.btn-back-home:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 30px rgba(0, 212, 255, 0.6);
}

/* 响应式 */
@media (max-width: 1200px) {
  .article-container {
    padding: 32px 120px 60px;
  }
}

@media (max-width: 900px) {
  .article-container {
    padding: 32px 60px 60px;
  }
}

@media (max-width: 768px) {
  .main-wrapper {
    padding: 0;
  }

  .article-container {
    padding: 24px 24px 60px;
  }
  
  .article-actions-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .article-title {
    font-size: 28px;
    line-height: 1.35;
  }

  .footer-actions-stats {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .footer-actions {
    width: 100%;
  }

  .action-btn {
    flex: 1;
    justify-content: center;
  }

  .footer-stats {
    font-size: 12px;
    width: 100%;
    justify-content: space-between;
  }

  .article-content {
    font-size: 16px;
    line-height: 1.75;
  }

  .article-content :deep(h1) { font-size: 26px; }
  .article-content :deep(h2) { font-size: 23px; }
  .article-content :deep(h3) { font-size: 20px; }
  .article-content :deep(h4) { font-size: 18px; }
}
</style>
